package com.csx.base.concurrency;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2024/11/25 周一 8:01
 */
public class TestSemaphoreLock {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            10,
            9999,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadPoolExecutor.AbortPolicy());

    static Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 3; i++) {
            int seriaNumber = i;
            executor.execute(() -> {
                try {
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String formattedDateTime = now.format(formatter);
                    semaphore.acquire();
                    System.out.println( formattedDateTime + " 获取数据库连接许可 序号: [ " + seriaNumber + " ]");
                    TimeUnit.SECONDS.sleep(100000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();
                }

            });
        }
        // 等待上面的线程全部启动,以此来将semaphore中的许可消耗完毕
        TimeUnit.SECONDS.sleep(5);
        new Thread(() -> {
            try {
                // 调试断点处
                semaphore.acquire();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                semaphore.release();
            }
        }).start();


    }
}
